package cn.wanho.handler;

import cn.wanho.rvo.ResultEnum;
import cn.wanho.rvo.ResultVO;
import cn.wanho.util.JsonUtil;

import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author qzw
 * 登录失败的处理流程
 */
@Component
public class UserAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        //登陆失败后返回json数据
        ResultVO result;
        //账号过期的操作
        if(e instanceof AccountExpiredException){
            result = ResultVO.failure(ResultEnum.USER_ACCOUNT_EXPIRED.getResCode(), ResultEnum.USER_ACCOUNT_EXPIRED.getResMsg());
        }else if(e instanceof BadCredentialsException){
                //密码错误
            result = ResultVO.failure(ResultEnum.USER_CREDENTIALS_ERROR.getResCode(),ResultEnum.USER_CREDENTIALS_ERROR.getResMsg());
        }else if(e instanceof CredentialsExpiredException){
            //登录的密码过期了
            result = ResultVO.failure(ResultEnum.USER_CREDENTIALS_EXPIRED.getResCode(), ResultEnum.USER_ACCOUNT_EXPIRED.getResMsg());

        }else if(e instanceof DisabledException){
            //账号不可用了
            result = ResultVO.failure(ResultEnum.USER_ACCOUNT_DISABLE.getResCode(), ResultEnum.USER_ACCOUNT_DISABLE.getResMsg());
        }else if (e instanceof LockedException){
            //账号被锁定了
           result = ResultVO.failure(ResultEnum.USER_ACCOUNT_LOCKED.getResCode(), ResultEnum.USER_ACCOUNT_DISABLE.getResMsg());
        }else if(e instanceof InternalAuthenticationServiceException){
            //账号不存在
            result = ResultVO.failure(ResultEnum.USER_ACCOUNT_NOT_EXIST.getResCode(), ResultEnum.USER_ACCOUNT_NOT_EXIST.getResMsg());
        }else{
            //其他的错误
            result = ResultVO.failure(ResultEnum.USER_ACCOUNT_USE_BY_OTHERS.getResCode(), ResultEnum.USER_ACCOUNT_USE_BY_OTHERS.getResMsg())
;        }

        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(JsonUtil.toJson(result));
    }
}
